package main

import (
	pb "ihos/ihos"
)

type wx_session struct {
	id                                       int32
	session, openid, unionid, appid, appname string
}

// func (w *wx_session) GetWXSession(id int32, name string) error {
// 	sql := "SELECT session,openid,unionid,appid,appname FROM wx_session WHERE id=$1 AND appname=$2"
// 	return DBConn.db.QueryRow(sql, id, name).Scan(&w.session, &w.openid, &w.unionid, &w.appid, &w.appname)
// }

// func (w *wx_session) SaveWXSession(session, openid, unionid, appid, appname string) (int32, error) {
// 	lastInsertId := int32(0)
// 	sql := "INSERT INTO wx_session(session,openid,unionid,appid,appname) VALUES($1,$2,$3,$4,$5) RETURNING id"
// 	err := DBConn.db.QueryRow(sql, session, openid, unionid, appid, appname).Scan(&lastInsertId)
// 	return lastInsertId, err
// }

func (w *wx_session) GetFromDB(id int32) error {
	sql := "SELECT id,session,openid,unionid,appid,appname FROM wx_session WHERE id=$1"
	return DBConn.db.QueryRow(sql, id).Scan(&w.id, &w.session, &w.openid, &w.unionid, &w.appid, &w.appname)
}

func (w *wx_session) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE wx_session set session=$1,openid=$2,unionid=$3,appid=$4,appname=$5 where id=$6 RETURNING id"
		err = DBConn.db.QueryRow(sql, w.session, w.openid, w.unionid, w.appid, w.appname, w.id).Scan(&w.id)
	} else { //insert
		sql = "INSERT INTO wx_session(session,openid,unionid,appid,appname) VALUES($1,$2,$3,$4,$5) RETURNING id"
		err = DBConn.db.QueryRow(sql, w.session, w.openid, w.unionid, w.appid, w.appname).Scan(&w.id)
	}
	return err
}

func (w *wx_session) fromPB(p *pb.WXSession) *wx_session {
	w.id = p.GetSESSIONID()
	w.session = p.GetSESSION()
	w.openid = p.GetOPENID()
	w.unionid = p.GetUNIONDID()
	// w.appid
	// w.appname
	return w
}

func (w *wx_session) toPB() *pb.WXSession {
	p := &pb.WXSession{
		SESSIONID: w.id,
		SESSION:   w.session,
		OPENID:    w.openid,
		UNIONDID:  w.unionid,
	}
	return p
}
